package com.yuke.cloud.service.wmc.controller.frontend;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.core.mq.RabbitSender;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.wmc.config.Printconfig;
import com.yuke.cloud.service.wmc.entity.*;
import com.yuke.cloud.service.wmc.printHttpUtil.HttpUtils;
import com.yuke.cloud.service.wmc.service.*;
import com.yuke.cloud.service.wmc.util.MD5;
import com.yuke.cloud.service.wmc.util.printUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/wms/print")
@Import(RabbitSender.class)
@Slf4j
public class GetPrintOrderController extends BaseController {
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private WmsStorageRecordService wmsStorageRecordService;
    @Autowired
    private WmsWarehouseShopService wmsWarehouseShopService;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private WmsAsyncService wmsAsyncService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private TaskExecutor taskExecutor;
    @Resource
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;
    @Autowired
    private LmsExpressService lmsExpressService;
    @Resource
    private WmsStockOutService wmsStockOutService;
    @Resource
    private WmsStorageService wmsStorageService;
    @Resource
    private WmsStockInService wmsStockInService;
    @Resource
    private CmcFeignApi cmcFeignApi;
    @Autowired
    private WmsPrinterService wmsPrinterService;




    @GetMapping("/justdoit")
    public void doit() {
        opcSendNotifyFeignApi.sendnotify("174106725740314624", "发货通知", "您的订单已经发货", 0);
    }

    @PostMapping("/doPrintOrderAndPrintIt")
    @ApiOperation(httpMethod = "POST", value = "获取单号LIST，并批量打印")
    public Wrapper addBatch(@RequestBody List<Long> orderIds) throws Exception {
        if (orderIds != null && orderIds.size() > 0){
           for (Long orderId : orderIds){
               Wrapper wrapper = add(orderId);
               if (wrapper.getCode() != 200){
                   return WrapMapper.error("发货过程出现错误："+ wrapper.getMessage());
               }
           }
           return WrapMapper.ok("成功");
        }
        return WrapMapper.error("参数错误！");
    }

    @GetMapping("/getPrintOrderAndPrintIt11")
    @ApiOperation(httpMethod = "GET", value = "获取单号，并打印")
    public Wrapper addPrintAndOrder(@Param("orderId") Long orderId) throws Exception {
            //todo 修改为5个方法：处理发货、处理库存、处理优惠券、处理发货通知、处理司机任务、处理兑换商品。异步执行
        String notifyMsg = "";

        Object getorderinforbyorderid = omcOrderFeignApi.getorderinforbyorderid(orderId);
        if (getorderinforbyorderid == null || getorderinforbyorderid.toString().equals("")) {
            System.out.println("获取订单信息为空");
            return WrapMapper.error("打印失败");
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(getorderinforbyorderid));
        //获取订单信息
        System.out.println("获取订单信息" + "============================================================");
        System.out.println(jsonObject);

        Long warehouseId = null;
        if (jsonObject.get("warehouseId") != null && PublicUtil.isNotEmpty(jsonObject.get("warehouseId").toString())) {
            warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
        }

        if (warehouseId == null) {
            // add by wg 20190501 根据店铺ID，获取仓库信息
            Example example = new Example(WmsWarehouseShop.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("shopId", Long.valueOf(jsonObject.get("shopId").toString()));
            List<WmsWarehouseShop> listWmsWarehouseShop = wmsWarehouseShopService.selectByExample(example);
            if (listWmsWarehouseShop == null || listWmsWarehouseShop.size() <= 0) {
                return WrapMapper.error();
            }

            warehouseId = listWmsWarehouseShop.get(0).getWarehouseId();
        }

        // add by wg 20190323 根据配送方式进行不同的处理
        // 获取配送方式 运送方式，0：同城即时达（仓库发还是店铺发暂时还不确定），1：物流快递，2：同城快送（一般24小时左右送达），3：即时达（云顶店铺发货），4：即时达（由仓库发货）
        if (PublicUtil.isEmpty(jsonObject.get("shippingType")) || PublicUtil.isEmpty(jsonObject.get("shippingType").toString())) {
            return WrapMapper.error("获取配送方式失败");
        }
        Byte shippingType = Byte.valueOf(jsonObject.get("shippingType").toString());

        //订单id和快递公司id
        String orderid = jsonObject.get("orderId").toString();
        String shopId = jsonObject.get("shopId").toString();
        Object goodsList = jsonObject.get("goodsList");
        JSONArray objects1 = JSON.parseArray(goodsList.toString());

        //获取spcid的名字
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < objects1.size(); i++) {
            // mod by wg 20190423
//                if (i != objects1.size()) {
            if (i != (objects1.size()-1)) {
                sb.append(objects1.getJSONObject(i).get("specId")).append(",");
            } else {
                sb.append(objects1.getJSONObject(i).get("specId"));
            }

        }
        List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb.toString());
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            return WrapMapper.error("获取商品详情失败");
        }
        System.out.println("商品规格的名字" + "============================================================");

        for (int i = 0; i < objects1.size(); i++) {
            // mod by wg 20190501 增加判断
            for (int j = 0; j < specInfoDtosBySpecIds.size(); j++) {
                if (objects1.getJSONObject(i).get("specId").toString().
                        equals(specInfoDtosBySpecIds.get(j).getSpecId().toString())) {
                    objects1.getJSONObject(i).put("specName", specInfoDtosBySpecIds.get(j).getSpecName());
                    // add by wg 20190501
                    objects1.getJSONObject(i).put("productId", specInfoDtosBySpecIds.get(j).getProductId());
                    // add by zyq 20210312
                    objects1.getJSONObject(i).put("unitNumber", specInfoDtosBySpecIds.get(j).getUnitNumber());
                    objects1.getJSONObject(i).put("unitSpec", specInfoDtosBySpecIds.get(j).getUnitSpec());
                    break;
                }
            }
        }
        System.out.println("商品规格的名字1"+JSON.toJSONString(objects1));

        String order_no = orderid;
        Long expressId = null;
        String waybill_no = orderid;  // 快递单号默认与订单号一样，对于自配送来说暂时没有快递单号

        if (shippingType == 1 && !Boolean.valueOf(jsonObject.get("isFactory").toString())) {  // 物流，厂家直销商品的快递由厂家直接发货
            //收货人的地址
            Map region_county_id = wmsWarehouseService.getaddressbyregionid(Long.valueOf(jsonObject.get("regionCountyId").toString()));
            System.out.println("收货人地址" + "============================================================");
            System.out.println(region_county_id);
            //仓库的地址
            // todo 需要根据订单所属仓库进行修改，订单为非厂家直销且为物流的订单才进入物流逻辑 20190717
            Map address = null;
            if (warehouseId == null) {
                address = wmsWarehouseService.getwarehouseaddressbyshopid(shopId);
            } else {
                address = wmsWarehouseService.getWarehouseAddress(warehouseId);
            }
            System.out.println("仓库地址，发货人地址" + "============================================================");
            System.out.println(address);

            // add by wg 20190219 获取快递公司
            String loginName = null;
            String loginPassword = null;
            String expressName = null;
            String expressShortName = null;
            String siteFlag = "";
            if (PublicUtil.isNotEmpty(jsonObject.get("expressId"))) {
                expressId = Long.valueOf(jsonObject.get("expressId").toString());
                LmsExpress lmsExpressTemp = lmsExpressService.findById(expressId);

                if (PublicUtil.isNotEmpty(lmsExpressTemp)) {
                    loginName = lmsExpressTemp.getLoginName();
                    loginPassword = lmsExpressTemp.getLoginPassword();
                    expressName = lmsExpressTemp.getExpressName();
                    expressShortName = lmsExpressTemp.getExpressShortName();
                    siteFlag = lmsExpressTemp.getSiteFlag();
                }
            }

            if (expressId == null || loginName == null) {  // 如果快递公司没有，则获取默认的
                Example example = new Example(LmsExpress.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("warehouseId", warehouseId);
                example.setOrderByClause("is_default DESC");
                List<LmsExpress> select = lmsExpressService.selectByExample(example);

                if (select == null || select.size() == 0) {
                    return WrapMapper.error("没有可用的快递公司");
                }
                loginName = select.get(0).getLoginName();
                loginPassword = select.get(0).getLoginPassword();
                expressId = select.get(0).getExpressId();
                expressName = select.get(0).getExpressName();
                expressShortName = select.get(0).getExpressShortName();
                siteFlag = select.get(0).getSiteFlag();
            }

            //从数据库获取默认的快递公司名称，测试暂时用顺丰
            // 先给对应的快递公司下单，获取电子面单号，然后调用接口打印
          //        String transid = "sf"; // todo 写死成顺丰的，需要参考快宝平台文档中的ID及数据库指定的快递公司
            String transid = expressShortName;  //add by wg 20190219
            String host = "http://kop.kuaidihelp.com";
            String path = "/api";
            String method = "POST";
            Map<String, String> headers = new HashMap<String, String>();
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("app_id", Printconfig.userId);
            bodys.put("method", "account.waybill.get");
            String ts = System.currentTimeMillis() + "";
            bodys.put("ts", ts);
            String str = Printconfig.userId + "account.waybill.get" + ts + Printconfig.apikey;
            String sign = MD5.MD5(str, "utf-8");
            bodys.put("sign", sign);
            Map<String, Object> data = new HashMap<String, Object>();//对应data
            //发送者(必填部分)
            Map<String, Object> sender = new HashMap<String, Object>();
            sender.put("city", address.get("regionCityName"));
            sender.put("province", address.get("regionProvinceName"));
            sender.put("address", address.get("address"));
            sender.put("mobile", address.get("telephone"));
            sender.put("district", address.get("regionCountyName"));
            sender.put("name", "裕客网");  // todo 写死，根据实际情况可修改
            //接受者(必填部分)
            Map<String, Object> recipient = new HashMap<String, Object>();
            recipient.put("city", region_county_id.get("regionCityName").toString());
            recipient.put("province", region_county_id.get("regionProvinceName"));
            recipient.put("address", jsonObject.get("address"));
            recipient.put("district", region_county_id.get("regionCountyName"));
            recipient.put("mobile", jsonObject.get("mobile"));
            recipient.put("tel", jsonObject.get("telephone"));
            recipient.put("name", jsonObject.get("consignee"));
            //商品(必填部分)
            Map<String, Object> commodities;
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < objects1.size(); i++) {
                commodities = new HashMap();
                Object specName = objects1.getJSONObject(i).get("specName");  // todo 可增加重量和备注，备注不是必选项，暂不加
//                Object weight = objects1.getJSONObject(i).get("goodsWeight");
                commodities.put("name", specName.toString());
//                commodities.put("weight", weight.toString());  // 非必填项
                list.add(commodities);
            }
            data.put("sender", sender);
            data.put("recipient", recipient);
            data.put("commodities", list);
            data.put("customer_name", loginName);//
            data.put("customer_password", loginPassword);
            data.put("order_id", jsonObject.get("orderId"));//todo 替换订单id
            data.put("shipper_type", transid);//todo 某个快递公司id
            //data.put("month_no", "7551234567");
            data.put("pay_type", 1);  // 支付方式 ：1-寄方支付，2-收方支付, 3-月结  // 月结需要填月结卡号
            data.put("site_flag", siteFlag);  // 申通必填，其他可选
            bodys.put("data", JSON.toJSONString(data));
            try {
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                System.out.println("进入这里吗");
                String s = EntityUtils.toString(response.getEntity());
                System.out.println(s);
                //获取response的body
                JSONObject jsonObject0 = JSONObject.parseObject(s);
                if ("0".equals(jsonObject0.get("code").toString())) {
                    JSONObject jsonObject1 = JSONObject.parseObject(jsonObject0.get("data").toString());
                    JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("result").toString());
                    waybill_no = jsonObject2.get("waybill_no").toString();//就是获取的快递单号
                    System.err.println("电子面单号码是" + waybill_no);
                    order_no = jsonObject2.get("order_no").toString();//商家自己的业务单号(订单号最好)

                    String pakgeName = jsonObject2.get("package_name").toString(); // 集包地名称
                    String originName = jsonObject2.get("origin_name").toString(); // 始发地名称
                    String originCode = jsonObject2.get("origin_code").toString(); // 始发地编号
                    String sortingCode = jsonObject2.get("sorting_code").toString(); // 分拣码
                    String destName = jsonObject2.get("dest_name").toString(); // 目的地名称
                    String routeCode = ""; // 二三段码
                    String sortation = destName; // 大字及一段码
                    if (PublicUtil.isNotEmpty(sortingCode)) {
                        String[] split = sortingCode.split("-");
                        if (PublicUtil.isNotEmpty(split[0])) {
                            sortation += split[0];
                        }

                        if (split.length >= 2 && PublicUtil.isNotEmpty(split[1])) {
                            routeCode = split[1];
                        }

                        if (split.length >= 3 && PublicUtil.isNotEmpty(split[2])) {
                            routeCode += " ";
                            routeCode += split[2];
                        }
                    }

                    String agentId = "";

                    // 获取该仓库下的打印机
                    if (warehouseId != null) {
                        Example example = new Example(WmsPrinter.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("warehouseId", warehouseId);
                        List<WmsPrinter> printers = wmsPrinterService.selectByExample(example);
                        if (printers != null && printers.size() > 0) {
                            agentId = printers.get(0).getAgentId();
                        }
                    }

                    if (PublicUtil.isEmpty(agentId)) {
                        return WrapMapper.ok("打印失败，找不到打印机");
                    }

                    Boolean printit = printUtil.printit(sender, recipient, orderid, waybill_no, transid, list
                            , pakgeName, originName, originCode, routeCode, sortation, agentId);//todo 要传入参数，发送者接受者，路由集宝地,根据情况可修改
                    if (!printit) {
                        System.out.println("打印失败");
                        return WrapMapper.ok("打印失败");
                    }

                    notifyMsg = "您的订单" + orderid + "已经发货，由 " + expressName + " 配送，运单号：" + waybill_no + "，请注意查收";
                } else {
                    return WrapMapper.error();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WrapMapper.error();
            }
        } else if (shippingType == 2) {  // 同城自配送
            expressId = 0L;  // 默认自配送为0
        } else {
            return WrapMapper.error("配送方式不支持，请确认");
        }

        //x修改订单配送表,同时订单状态
        Map map = new HashMap();
        map.put("orderId", order_no);
        if (expressId != null) {
            map.put("ExpressCompanyId", expressId.toString());
        }
        map.put("TrackingNumber", waybill_no);

        //首重续重没有保存

        // todo 要获取product_id
        if (shippingType != 1) {  // 获取productId，当shippingType为物流快递时，productId已经获取
            List<Long> specIds = new ArrayList<>();
            for (int i = 0; i < objects1.size(); i++) {
                specIds.add(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()));
            }

            Example exampleStorage = new Example(WmsStorage.class);
            Example.Criteria criteriaStorage = exampleStorage.createCriteria();
            criteriaStorage.andEqualTo("warehouseId", warehouseId);
            criteriaStorage.andIn("specId", specIds);
            List<WmsStorage> listWmsStorage = wmsStorageService.selectByExample(exampleStorage);
            if (listWmsStorage == null || listWmsStorage.size() <= 0) {
                return WrapMapper.error();
            }

            for (int i = 0; i < objects1.size(); i++) {
                for (int j = 0; j < listWmsStorage.size(); j++) {
                    if (objects1.getJSONObject(i).get("specId").toString().
                            equals(listWmsStorage.get(j).getSpecId().toString())) {
                        objects1.getJSONObject(i).put("productId", listWmsStorage.get(j).getProductId());

                        break;
                    }
                }
            }
        }

        //生成订单，库存不变，锁定增加，支付成功，库存不变，锁定不变。打印发货成功，锁定减少，库存减少

        // add by wg 20190605 判断秒杀商品
        List<CmsSecKillSkuDto> cmsSecKillSkuDtos = wmsStorageService.getSecKillSkus();
        String strUserId = jsonObject.get("userId").toString();

        List<ProdSpecInfoDto> prodSpecInfoDtos = new ArrayList<>();

        for (int i = 0; i < objects1.size(); i++) {
            if (Boolean.valueOf(jsonObject.get("isFactory").toString())) {  // 厂家直销
                wmsWarehouseService.updateFactoryStorage(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()), -Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
            } else {


                WmsStorage wmsStorage = new WmsStorage();
                wmsStorage.setWarehouseId(warehouseId);
                wmsStorage.setSpecId(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()));
                List<WmsStorage> list = wmsStorageService.select(wmsStorage);
                for(WmsStorage item:list){
                    //todo 20191105 防止库存不足报错，如果库存数小于出库数，让库存数=出库数，
                    if (item.getNumber() < Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString())){
                        item.setNumber(Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                    }
                    //todo 如果库存减锁定库存小于0，让锁定库存=库存
                    if(item.getNumber()-item.getLockNumber() < 0){
                        item.setLockNumber(item.getNumber());
                    }

                    //todo 如果锁定库存小于出库数，让锁定库存=出库数
                    if(item.getLockNumber() < Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString())){
                        item.setLockNumber(Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                    }
                    //todo 如果存货《 出库数，存货数=num-lock_number-goodsNum，生产日期变更为最新
                    //todo 否则,存货数=remainder-goodsNum
                    if (item.getRemainder() <= Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString())){
                        if (item.getNumber()-item.getLockNumber()-Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()) > 0){
                            item.setRemainder(item.getNumber()-item.getLockNumber()-Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                        }else{
                            item.setRemainder(0);
                        }

                        //取出生产日期,入库日期
                        Example exampleStockIn = new Example(WmsStockIn.class);
                        Example.Criteria criteriaStockIn = exampleStockIn.createCriteria();
                        exampleStockIn.setOrderByClause("mfg_date desc");
                        criteriaStockIn.andEqualTo("warehouseId", warehouseId);
                        criteriaStockIn.andEqualTo("specId", wmsStorage.getSpecId());
                        List<WmsStockIn> listWmsStockIn = wmsStockInService.selectByExample(exampleStockIn);
                        if (listWmsStockIn != null && listWmsStockIn.size() > 0){
                            item.setMfgDate(listWmsStockIn.get(0).getMfgDate());
                            item.setStockinDate(listWmsStockIn.get(0).getInboundTime());
                        }

                    }else{
                        item.setRemainder(item.getRemainder()-Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                    }
                    wmsStorageService.update(item);
                }//todo end
                //
                wmsStorageService.updateWarehouseStorage(warehouseId,
                        Long.valueOf(objects1.getJSONObject(i).get("specId").toString()),
                        -Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()),
                        -Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));

                // add by wg 20190501 增加出库记录
                Long productId = Long.valueOf(objects1.getJSONObject(i).get("productId").toString());

                WmsStockOut wmsStockOut = new WmsStockOut();
                wmsStockOut.setStockOutId(super.generateId());
                wmsStockOut.setWarehouseId(warehouseId);
                wmsStockOut.setOutType((byte)0);
                wmsStockOut.setSpecId(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()));
                wmsStockOut.setProductId(productId);
                wmsStockOut.setOutNumber(Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                wmsStockOut.setOrderId(Long.valueOf(orderid));
                LoginAuthDto loginAuthDto = super.getLoginAuthDto();
                wmsStockOut.setUpdateId(loginAuthDto.getUserId());
                Date date = new Date();
                wmsStockOut.setOutboundTime(date);
                wmsStockOut.setUpdateTime(date);
                taskExecutor.execute(() -> wmsStockOutService.save(wmsStockOut));


                //更新库存记录表
                System.out.println("更新库存记录表"+JSON.toJSONString(objects1));
                WmsStorageRecord wmsStorageRecord = new WmsStorageRecord();
                if (Long.valueOf(objects1.getJSONObject(i).get("unitSpec").toString()) > 0){
                    wmsStorageRecord.setSpecId(Long.valueOf(objects1.getJSONObject(i).get("unitSpec").toString()));
                }else{
                    wmsStorageRecord.setSpecId(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()));
                }
                wmsStorageRecord.setNumber(Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                wmsStorageRecord.setWarehouseId(warehouseId);
                wmsStorageRecordService.updateByWmsStorageRecord(wmsStorageRecord);
            }

            for (CmsSecKillSkuDto cmsSecKillSkuDto : cmsSecKillSkuDtos) {
                if (cmsSecKillSkuDto.getSpecId().longValue() == Long.valueOf(objects1.getJSONObject(i).get("specId").toString()).longValue()) {
                    cmsSecKillSkuDto.setStoreCount(-Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                    cmsSecKillSkuDto.setLockCount(-Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
                    cmsSecKillSkuDto.setSaledCount(Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));

                    // add by wg 20190606 增加秒杀活动商品的处理 增加用户购买信息
                    int count = 0;
                    if (redisTemplate.hasKey(RedisKeyUtil.getSecKillSkuUserBuy(String.valueOf(cmsSecKillSkuDto.getSecKillId()), String.valueOf(cmsSecKillSkuDto.getSpecId()), strUserId))) {
                        count = (int)redisTemplate.opsForValue().get(RedisKeyUtil.getSecKillSkuUserBuy(String.valueOf(cmsSecKillSkuDto.getSecKillId()), String.valueOf(cmsSecKillSkuDto.getSpecId()), strUserId));
                    }

                    count += Integer.valueOf(objects1.getJSONObject(i).get("goodsNum").toString());
                    redisTemplate.opsForValue().set(RedisKeyUtil.getSecKillSkuUserBuy(String.valueOf(cmsSecKillSkuDto.getSecKillId()), String.valueOf(cmsSecKillSkuDto.getSpecId()), strUserId), count);
                }
            }

            // 销量更新
            ProdSpecInfoDto prodSpecInfoDto = new ProdSpecInfoDto();
            prodSpecInfoDto.setSpecId(Long.valueOf(objects1.getJSONObject(i).get("specId").toString()));
            prodSpecInfoDto.setSaleCount(Long.valueOf(objects1.getJSONObject(i).get("goodsNum").toString()));
            prodSpecInfoDtos.add(prodSpecInfoDto);
        }

        // add by wg 20190606 增加秒杀活动商品的处理
        cmcFeignApi.updateSecKillSkusCount(cmsSecKillSkuDtos);

        // 销量更新
       // pmcFeignApi.updateSpecSaleCount(prodSpecInfoDtos);

        // todo 如果此单使用了优惠券，标记使用状态
        System.out.println("如果此单使用了优惠券，标记使用状态");
        String id = "CouponReceiveIdAndOrderId:"+orderid;
        //CmsCouponUserDto ccud = (CmsCouponUserDto)redisTemplate.opsForValue().get(id);
        //JSONObject jsonOb = JSON.parseObject(redisTemplate.opsForValue().get(id));
        Map<String,String> ccud = (Map<String, String>) redisTemplate.opsForValue().get(id);
        if (ccud != null){
           redisTemplate.delete(id);
        }

        //发货时，如果有兑奖商品，改变兑奖单的状态
        taskExecutor.execute(() -> omcOrderFeignApi.sendAwardRecord(orderId));


        //保存物流单，修改订单状态为已经发货同时返回本订单的用户id，用来发送信鸽通知
        taskExecutor.execute(() -> omcOrderFeignApi.saveorderDeliver(map));

        if (PublicUtil.isEmpty(notifyMsg)) {
            notifyMsg = "您的订单" + orderid + "已经发货";
        }

        String orderType = jsonObject.get("orderType").toString();
        Object userId1 = jsonObject.get("userId");
//        System.out.println(userId);
        MsgNotificationBody msg = new MsgNotificationBody();
        msg.setTitle("发货通知");
        msg.setContent(notifyMsg);
        msg.setTime(new Date());
        msg.setOrderType((byte) 1);
        msg.setMsgType("orderMsg");
        if(orderType.equals("1")){
            msg.setReceiveType((byte) 1);
        }else if(orderType.equals("2")){
            msg.setReceiveType((byte) 3);
        }

        opcSendNotifyFeignApi.sendnotify(userId1.toString(), "发货通知", notifyMsg, 0);
        opcSendNotifyFeignApi.sendnotify(userId1.toString(), "发货通知", JSON.toJSONString(msg), 1);

        return WrapMapper.ok("成功");
    }

    @PostMapping("/getorderinfo")
    public Wrapper getorderinfo(@RequestBody JSONObject jsonObject) throws Exception {
        String json = jsonObject.get("userid").toString();
        System.out.println(json);
        Object getit = omcOrderFeignApi.getit(json);
        if (getit == null || getit.toString().equals("")) {
            System.out.println("退出wmc-getorderinfo-omcOrderFeignApi.getit(json)->null");
            return WrapMapper.ok("空");
        }
        String s = JSON.toJSONString(getit);
        JSONArray objects = JSON.parseArray(s);
        if (objects.size() == 0) {
            return WrapMapper.ok();
        }
        for (int i = 0; i < objects.size(); i++) {
            JSONObject jsonObject2 = objects.getJSONObject(i);
            Object orderId = jsonObject2.get("orderId");
            System.out.println("orderId=" + orderId);

            Map map = omcOrderFeignApi.getmapbyorderid(Long.valueOf(orderId.toString()));
            if (map == null || map.isEmpty()) {
                jsonObject2.put("logistics", "空");
            } else {

                // todo add by wg 20190322 对于自配送方式，暂时作特殊处理,同城快送为自配送方式
                // 运送方式，0：同城即时达（仓库发还是店铺发暂时还不确定），1：物流快递，2：同城快送（一般24小时左右送达），3：即时达（云顶店铺发货），4：即时达（由仓库发货）
                Byte shippingType = Byte.valueOf(jsonObject2.get("shippingType").toString());
                map.put("shippingType", shippingType);
                map.put("sendTime", jsonObject2.get("sendTime"));
                if (shippingType != 1) {  // 除物流外的配送方式
                    // 同城不显示
//                    String sendTime = map.get("sendTime").toString();
//                    JSONObject resultJson = new JSONObject();
//                    resultJson.put("time", sendTime);
//                    resultJson.put("context", "由仓库 发往 用户");
//                    jsonObject2.put("logistics", resultJson);
                } else {
                    String expressShortName = "";
                    // 根据transferComponey获取对应的快递公司编码
                    LmsExpress lmsExpress = lmsExpressService.findById(Long.valueOf(map.get("transferComponey").toString()));

                    if (lmsExpress != null) {
                        expressShortName = lmsExpress.getExpressShortName();
                    }

                    if (PublicUtil.isEmpty(expressShortName)) {
                        return WrapMapper.ok("空");
                    }

                    map.put("transferComponey", expressShortName);
                    map.put("expressName", lmsExpress.getExpressName());

                    Wrapper logistics = getLogistics(map);
                    Object result1 = logistics.getResult();

                    // mod by wg 20190323
                    if(result1==null||result1.toString().equals("")){
                        jsonObject2.put("logistics", "空");
                    } else {
//                        JSONArray dataArray = (JSONArray)result1;
//                        JSONObject jsonObject1 = JSONObject.parseObject(dataArray.get(0).toString());
//                        JSONArray data1 = JSON.parseArray(jsonObject1.get("data").toString());  // 没有返回状态，是派送中还是签收，状态在jsonObject1中
//                        result1 = data1;

                        jsonObject2.put("logistics", result1);
                    }
                }
            }

        }
        return WrapMapper.ok(objects);
    }




    /**
     * 查询物流状态，包括轨迹跟踪
     * 参考：https://open.kuaidihelp.com/api/1003
     * @param map
     * @return
     * @throws Exception
     */
    public Wrapper getLogistics(Map map) throws Exception {
        /* String orderid = jsonObject.get("orderid").toString();
        OdsOrderDelivery odsOrderDelivery = new OdsOrderDelivery();
        odsOrderDelivery.setOrderId(Long.valueOf(orderid));
        List<OdsOrderDelivery> select = odsOrderDeliveryService.select(odsOrderDelivery);*/
      /*  List select = new ArrayList();
        if (select.size() == 0) {
            return WrapMapper.ok("空");
        }*/
        //获取物流单号
        // String trackingNumber = select.get(0).getTrackingNumber();

        JSONObject jsonObjectRet = new JSONObject();

        // todo add by wg 20190323 对于自配送，由于目前没有自己的体系，自配送时，getLogistics方法一般由系统在7天后查询物流状态并改变订单状态，此时认为已经送达
        Byte shippingType = Byte.valueOf(map.get("shippingType").toString());
        log.info("查询物流，配送方式：{}", shippingType);
        if (shippingType != 1) {  // 除快递外的其他配送方式
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("no", map.get("trackingNumber").toString());
            jsonObject.put("brand", "yuke");
            jsonObject.put("status", "delivering");
            JSONObject jsonObjectData = new JSONObject();

            if (map.get("sendTime") instanceof String) {
                jsonObjectData.put("time", map.get("sendTime").toString());
            } else {
                Date sendTime = (Date)map.get("sendTime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                jsonObjectData.put("time", sdf.format(sendTime));
            }
//            log.info("+++++++++++sendTime={}", map.get("sendTime").toString());
            jsonObjectData.put("context", "由仓库 发往 用户");
            JSONArray jsonArrayData = new JSONArray();
            jsonArrayData.add(jsonObjectData);
            jsonObject.put("data", jsonArrayData);

            JSONArray jsonArrayResult = new JSONArray();
            jsonArrayResult.add(jsonObject);

            jsonObjectRet.put("expressName",  "平台配送");
            jsonObjectRet.put("trackingNumber", map.get("trackingNumber").toString());

            jsonObjectRet.put("result", "success");
            jsonObjectRet.put("info", jsonArrayResult);

//            return WrapMapper.ok(jsonArrayResult);
            return WrapMapper.ok(jsonObjectRet);
        }

        String trackingNumber = map.get("trackingNumber").toString();
        String transferComponey = map.get("transferComponey").toString();
        String host = "http://kop.kuaidihelp.com";
        String path = "/api";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("app_id", Printconfig.userId);
        bodys.put("method", "express.info.get");
        String ts = System.currentTimeMillis() + "";
        bodys.put("ts", ts);
        String str = Printconfig.userId + "express.info.get" + ts + Printconfig.apikey;
        String sign = null;
        try {
            sign = MD5.MD5(str, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        bodys.put("sign", sign);
        Map<String, Object> data = new HashMap<String, Object>();
        System.err.println(trackingNumber);
        System.err.println(transferComponey);
        data.put("waybill_no", trackingNumber);
        data.put("exp_company_code", transferComponey);
        data.put("result_sort", "0");  // 返回的物流信息排序（根据物流时间，0-降序排列，1-升序排列，默认值0）
        bodys.put("data", JSON.toJSONString(data));
        //todo 快递单号，快递公司名字sf，zt等
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        // todo for test 20190724
        JSONObject jsonObject0 = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));

        jsonObjectRet.put("expressName",  map.get("expressName").toString());
        jsonObjectRet.put("trackingNumber", trackingNumber);

        if ("0".equals(jsonObject0.get("code").toString())) {
            JSONArray data3 = JSON.parseArray(jsonObject0.get("data").toString());

            JSONObject jsonObject1 = JSONObject.parseObject(data3.get(0).toString());
            JSONArray data1 = JSON.parseArray(jsonObject1.get("data").toString());

            jsonObjectRet.put("result", "success");
            jsonObjectRet.put("info", data1);


            return WrapMapper.ok(jsonObjectRet);
        } else if ("201101".equals(jsonObject0.get("code").toString())) {
            jsonObjectRet.put("result", "fail");
            jsonObjectRet.put("info", jsonObject0.get("msg").toString());
//            return WrapMapper.error(jsonObject0.get("msg").toString());
            return WrapMapper.ok(jsonObjectRet);
        }
//        return WrapMapper.error();
        jsonObjectRet.put("result", "fail");
        jsonObjectRet.put("info", "查询失败");
        return WrapMapper.ok(jsonObjectRet);
    }

    //todo 修改为5个方法：处理发货、处理库存、处理优惠券、处理发货通知、处理司机任务、处理兑换商品。异步执行
    @GetMapping("/getPrintOrderAndPrintIt")
    @ApiOperation(httpMethod = "GET", value = "获取单号，并打印")
    public Wrapper add(@Param("orderId") Long orderId) {
        Long aaa=System.currentTimeMillis();
        System.out.println(aaa);
        Object getorderinforbyorderid = omcOrderFeignApi.getorderinforbyorderid(orderId);
        if (getorderinforbyorderid == null || getorderinforbyorderid.toString().equals("")) {
            System.out.println("获取订单信息为空");
            return WrapMapper.error("打印失败,订单信息为空！");
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(getorderinforbyorderid));

        Long warehouseId = null;
        if (jsonObject.get("warehouseId") != null && PublicUtil.isNotEmpty(jsonObject.get("warehouseId").toString())) {
            warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
        }

        if (warehouseId == null) {
            // add by wg 20190501 根据店铺ID，获取仓库信息
            Example example = new Example(WmsWarehouseShop.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("shopId", Long.valueOf(jsonObject.get("shopId").toString()));
            List<WmsWarehouseShop> listWmsWarehouseShop = wmsWarehouseShopService.selectByExample(example);
            if (listWmsWarehouseShop == null || listWmsWarehouseShop.size() <= 0) {
                return WrapMapper.error();
            }
            warehouseId = listWmsWarehouseShop.get(0).getWarehouseId();
        }

        // add by wg 20190323 根据配送方式进行不同的处理
        // 获取配送方式 运送方式，0：同城即时达（仓库发还是店铺发暂时还不确定），1：物流快递，2：同城快送（一般24小时左右送达），3：即时达（云顶店铺发货），4：即时达（由仓库发货）
        if (PublicUtil.isEmpty(jsonObject.get("shippingType")) || PublicUtil.isEmpty(jsonObject.get("shippingType").toString())) {
            return WrapMapper.error("获取配送方式失败");
        }

        String strUserId = jsonObject.get("userId").toString();
        //订单id和快递公司id
        String orderid = jsonObject.get("orderId").toString();
        LoginAuthDto loginAuthDto = super.getLoginAuthDto();
        Long userId =  loginAuthDto.getUserId();
        Object goodsList = jsonObject.get("goodsList");
        JSONArray objects1 = JSON.parseArray(goodsList.toString());

        //获取spcid的名字
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < objects1.size(); i++) {

            if (i != (objects1.size()-1)) {
                sb.append(objects1.getJSONObject(i).get("specId")).append(",");
            } else {
                sb.append(objects1.getJSONObject(i).get("specId"));
            }

        }
        List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb.toString());
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            return WrapMapper.error("获取商品详情失败");
        }
        System.out.println("商品规格的名字" + "============================================================");

        for (int i = 0; i < objects1.size(); i++) {
            // mod by wg 20190501 增加判断
            for (int j = 0; j < specInfoDtosBySpecIds.size(); j++) {
                if (objects1.getJSONObject(i).get("specId").toString().
                        equals(specInfoDtosBySpecIds.get(j).getSpecId().toString())) {
                    objects1.getJSONObject(i).put("specName", specInfoDtosBySpecIds.get(j).getSpecName());
                    // add by wg 20190501
                    objects1.getJSONObject(i).put("productId", specInfoDtosBySpecIds.get(j).getProductId());
                    // add by zyq 20210312
                    objects1.getJSONObject(i).put("unitNumber", specInfoDtosBySpecIds.get(j).getUnitNumber());
                    objects1.getJSONObject(i).put("unitSpec", specInfoDtosBySpecIds.get(j).getUnitSpec());
                    break;
                }
            }
        }
        System.out.println("商品规格的名字1"+JSON.toJSONString(objects1));

        try {
            Integer po = wmsAsyncService.printOrder(jsonObject,warehouseId);
            if (po == -1) {
                return WrapMapper.error("没有可用的快递公司");
            }else if(po == -2) {
                return WrapMapper.ok("打印失败，找不到打印机");
            }else if(po == -3) {
                return WrapMapper.ok("打印失败");
            }else if(po == -4) {
                return WrapMapper.error("打印失败，请确认");
            }else if(po == -5) {
                return WrapMapper.error("配送方式不支持，请确认");
            }
        }catch (Exception e){
            return WrapMapper.error();
        }

        //更新库存表
        wmsAsyncService.updateWmsStoage(objects1,warehouseId);
        // add by wg 20190501 增加出库记录
        wmsAsyncService.saveWmsStockOut(objects1,warehouseId, orderId,userId);
        //更新库存记录表
        wmsAsyncService.updateWmsStorageRecorder(objects1,warehouseId);

        wmsAsyncService.updateCmsSecKill(objects1,strUserId);




        // todo 如果此单使用了优惠券，标记使用状态
        System.out.println("如果此单使用了优惠券，标记使用状态");
        String id = "CouponReceiveIdAndOrderId:"+orderid;

        Map<String,String> ccud = (Map<String, String>) redisTemplate.opsForValue().get(id);
        if (ccud != null){
            redisTemplate.delete(id);
        }

        //发货时，如果有兑奖商品，改变兑奖单的状态
        taskExecutor.execute(() -> omcOrderFeignApi.sendAwardRecord(orderId));


        return WrapMapper.ok("成功");
    }

    public static void main(String[] args) throws Exception {
        //Map map = new HashMap();
//        map.put("trackingNumber", "75117525813426");
//        map.put("transferComponey", "zt");
//        map.put("trackingNumber", "233729290001");
//        map.put("transferComponey", "sf");
//        map.put("expressName", "sf");
//        map.put("shippingType", 1);
//        map.put("sendTime", new Date());
//        Wrapper logistics = new GetPrintOrderController().getLogistics(map);

        //new GetPrintOrderController().testAsyncController();

    }


}
